import React, { Component } from 'react'
import request from '../util/request'
import IsLogin from '../util/isLogin'

class Add extends Component {
    state = {
        title:'',
        con:''
    }

    componentDidMount(){
        if(localStorage.getItem('obj')){
            let {title,con} = JSON.parse(localStorage.getItem('obj'));
            this.setState({
                title,
                con
            })
        }
    }

    render() {
        let {title,con} = this.state;
        
        return (
            <div>
                <input type="text" placeholder="title" value={title} name="title" onChange={this.change}/>
                <input type="text" placeholder="con" value={con} name="con"  onChange={this.change}/>
                <button onClick={this.add}>发表博客</button>
            </div>
        )
    }

    change = (e) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    add = () => {
        let {title,con} = this.state;
        let url = '',
            type = '';
        let id = this.props.history.location.state && this.props.history.location.state.id;
        if(id){
            //编辑  put 
            url = `/api/blog/${id}`;
            type = 'put';
        }else{
            //添加  post
            url = '/api/blog';
            type = 'post';
        }
        request[type](url,{title,con}).then(res => {
            console.log(res);
            if(res.code === 1){
                localStorage.removeItem('obj');
                this.props.history.push('/home');
            }
        })
    }
}

export default IsLogin(Add)